﻿using Common;
using Common.Entity;
using Common.Utility;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeToolBox.Form
{
    public partial class FieldPartZhForm : UIForm
    {
        public FieldPartZhForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPartZhForm_Load(object sender, EventArgs e)
        {
            try
            {
                string fileurl = Config.BeflamInIUrl;
                if (File.Exists(fileurl))
                {
                    text_url.Text = INIHelper.INIRead("配置信息", "URL", fileurl);
                    text_session.Text = INIHelper.INIRead("配置信息", "SessionID", fileurl);
                    text_appid.Text = INIHelper.INIRead("配置信息", "AppID", fileurl);
                    text_table.Text = INIHelper.INIRead("配置信息", "Table", fileurl);
                    text_type.Text = INIHelper.INIRead("配置信息", "StateType", fileurl);
                    text_column.Text = INIHelper.INIRead("配置信息", "ColumnCount", fileurl);
                }
                else
                {
                    string folderPath = fileurl.Split((fileurl.Split("\\").Last()))[0];
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    writerSetting();
                }
            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }






        /// <summary>
        /// 写入配置
        /// </summary>
        private void writerSetting()
        {
            try
            {
                string fileurl = Config.BeflamInIUrl;
                INIHelper.INIWrite("配置信息", "URL", text_url.Text, fileurl);
                INIHelper.INIWrite("配置信息", "SessionID", text_session.Text, fileurl);
                INIHelper.INIWrite("配置信息", "AppID", text_appid.Text, fileurl);
                INIHelper.INIWrite("配置信息", "Table", text_table.Text, fileurl);
                INIHelper.INIWrite("配置信息", "StateType", text_type.Text, fileurl);
                INIHelper.INIWrite("配置信息", "ColumnCount", text_column.Text, fileurl);


            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }


        /// <summary>
        ///  保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
            writerSetting();
            ShowSuccessTip("保存成功", 1500);
        }

        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(text_url.Text.Trim())) throw new Exception("url不能为空");
                if (string.IsNullOrWhiteSpace(text_session.Text.Trim())) throw new Exception("sessionID不能为空");
                if (string.IsNullOrWhiteSpace(text_appid.Text.Trim())) throw new Exception("应用名不能为空");
                if (string.IsNullOrWhiteSpace(text_table.Text.Trim())) throw new Exception("表名不能为空不能为空");
                if (string.IsNullOrWhiteSpace(text_type.Text.Trim())) throw new Exception("类型不能为空");
                if (string.IsNullOrWhiteSpace(text_column.Text.Trim())) throw new Exception("列数不能为空");
                if (string.IsNullOrWhiteSpace(richTextBox2.Text.Trim())) throw new Exception("转换后的字段不能为空");


                string urlstr = text_url.Text.Trim();
                string sessionid = text_session.Text.Trim();
                string appid = text_appid.Text.Trim();
                string tablestr = text_table.Text.Trim();
                string type = text_type.Text.Trim();
                int column = int.Parse(text_column.Text.Trim()) - 1;
                List<string> listfield = richTextBox2.Text.Trim().Split('\n').ToList();

                HttpHelper httphelper = new HttpHelper();
                RequestEntity requestentity = new RequestEntity()
                {
                    sessionID = sessionid,
                    module = "Beflam.Framework.Service.CodeUtilPro.CodeUtilProService",
                    function = "Refresh1",
                    data = new
                    {
                        DbKey = "",
                        EntitySource = "codeUtilProfile",
                        Fields = new
                        {
                            PRJ_NO = appid,
                            InitMode = "load-from-schema",
                            InitId = tablestr,
                            IsCustomerLayout = true,
                            Columns = 3
                        }
                    }
                };
                string fieldpart = httphelper.PostRequest(urlstr, requestentity);

                FieldPartLayoutData fieldpartEntity = JsonConvert.DeserializeObject<FieldPartLayoutData>(fieldpart);
                if (fieldpartEntity.code != 0) throw new Exception("生成失败！");

                //获取Schema
                BeflamToolManager manager = new BeflamToolManager();
                SchemaData schema = manager.GetSchema(urlstr, appid, sessionid, tablestr);
                //生成模板
                text_filename.Text = manager.SaveField(urlstr, sessionid, tablestr, fieldpartEntity, schema, type, listfield, column);

                ShowSuccessTip("创建成功", 1500);
            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }

        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(richTextBox1.Text)) throw new Exception("转换字段不能为空");
                string text1 = richTextBox1.Text;
                string text2 = "";
                lab_fieldcount.Text = "";
                using (StringReader reader = new StringReader(text1))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Contains("[FIELD_"))
                        {
                            string fieldValue = Regex.Match(line, @"\[FIELD_(.*?)\]").Groups[1].Value;
                            text2 += fieldValue.Trim() + Environment.NewLine;
                        }
                    }
                }
                richTextBox2.Text = text2;
                lab_fieldcount.Text = "转换后字段数：" + (richTextBox2.Text.Split('\n').ToList().Count - 1).ToString();
            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }


    }
}
